package com.wj.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * 通过 nacos 下发动态路由配置，监听 Nacos 中路由配置变更
 *     DependsOn:在 {} 列表 bean 初始化之后 再初始化当前 bean
 */
@Slf4j
@Component
@DependsOn({"gatewayConfig"})
public class DynamicRouteServiceImplByNacos {

    //Nacos 配置服务
    private ConfigService configService;

    private final DynamicRouteServiceImpl dynamicRouteService;

    public DynamicRouteServiceImplByNacos(DynamicRouteServiceImpl dynamicRouteService){
        this.dynamicRouteService = dynamicRouteService;
    }

    /**
     *  Bean 在容器中构造完成之后会执行 init 方法
     */
    @PostConstruct
    public void init(){
        log.info("gateway route init ...");
        try {
            //初始化 Nacos 配置客户端
            configService = initConfigService();
            if (Objects.isNull(configService)){
                log.error("init config service fail");
                return;
            }
            //通过 Nacos Config 并指定路由配置路径去获取路由配置
            String configInfo = configService.getConfig(
                    GatewayConfig.NACOS_ROUTE_DATA_ID,
                    GatewayConfig.NACOS_ROUTE_GROUP,
                    GatewayConfig.DEFAULT_TIMEOUT
            );
            log.info("get current gateway config: [{}]",configInfo);
            //反序列化
            List<RouteDefinition> definitions = JSON.parseArray(configInfo, RouteDefinition.class);
            if (!CollectionUtils.isEmpty(definitions)){
                for (RouteDefinition definition : definitions) {
                    log.info("init gateway config: [{}]",definition.toString());
                    dynamicRouteService.addRouteDefinition(definition);
                }
            }
        }catch (Exception e){
            log.error("gateway route init has some error: [{}]",e.getMessage(), e);
        }
        //设置监听器
        dynamicRouteByNacosListener(GatewayConfig.NACOS_ROUTE_DATA_ID,GatewayConfig.NACOS_ROUTE_GROUP);
    }

    /**
     * 初始化 Nacos Config
     *
     * @return
     */
    private ConfigService initConfigService(){
        try {
            Properties properties = new Properties();
            properties.setProperty(PropertyKeyConst.SERVER_ADDR,GatewayConfig.NACOS_SERVER_ADDR);
            properties.setProperty(PropertyKeyConst.NAMESPACE,GatewayConfig.NACOS_NAMESPACE);
            properties.setProperty(PropertyKeyConst.USERNAME,"nacos");
            properties.setProperty(PropertyKeyConst.PASSWORD,"nacos");
            return configService = NacosFactory.createConfigService(properties);
        } catch (Exception e) {
            log.info("init gateway nacos config error: [{}]",e.getMessage(),e);
            return null;
        }
    }

    /**
     * 监听 Nacos 下发的动态路由配置
     *
     * @param dataId
     * @param group
     */
    private void dynamicRouteByNacosListener(String dataId, String group){
        //给 Nacos Config 客户端添加一个监听器
        try {
            configService.addListener(dataId, group, new Listener() {

                /**
                 * 自己提供线程池执行操作
                 * @return
                 */
                @Override
                public Executor getExecutor() {
                    return null;
                }

                /**
                 * 监听器收到配置更新
                 *
                 * @param configInfo  Nacos 中最新的配置定义
                 */
                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.info("start to update config: [{}]", configInfo);
                    List<RouteDefinition> definitions = JSON.parseArray(configInfo, RouteDefinition.class);
                    log.info("update route: [{}]", definitions.toString());
                    dynamicRouteService.updateList(definitions);
                }
            });
        } catch (NacosException e) {
            log.info("dynamic update gateway config error: [{}]",e.getMessage(),e);
        }
    }

}
